<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    /**
     * Authenticates a user.
     * @return boolean whether authentication succeeds.
     */
    public $_id = NULL;

    const ERROR_NO_ACCESS = 3;
    const ERROR_BAD_LOGINS = 4;
    const ERROR_BAD_IP = 5;

    public function authenticate() {
        $username = strtolower($this->username);
        $user = User::model()->find('LOWER(`username`)=?', array($username));
        $ip = $_SERVER["REMOTE_ADDR"];
        if ($user === null)
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        else if ($user->password != $this->password)
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        else if ($user->locked == "1")
            $this->errorCode = self::ERROR_NO_ACCESS;
        else if ($user->bad_logins > 50)
            $this->errorCode = self::ERROR_BAD_LOGINS;
        else if (!empty($user->login_ip) && $user->login_ip != $ip)
            $this->errorCode = self::ERROR_BAD_IP;
        else {
            $this->_id = $user->id;
            $this->username = $user->username;
            $this->errorCode = self::ERROR_NONE;
            //$user->last_login = "2012-05-14 01:02:03";
            $user->last_login = date("Y-m-D H:M:i");
            $user->logged_ip = $ip;
            $user->bad_logins = "0";
            $user->save(false);
        }

        return $this->errorCode == self::ERROR_NONE;
    }

    public function getId() {
        return $this->_id;
    }

}